<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="header">
			<view class="header-left">
				<text class="header-title">公告管理</text>
				<text class="header-desc">管理您发布的通知公告</text>
			</view>
			<view class="header-right">
				<button class="add-btn" @click="navigateTo('/packageadmin/admin/notice-upload')">新增公告</button>
			</view>
		</view>
		
		<!-- 公告列表 -->
		<view class="notice-list" v-if="!loading">
			<view class="empty-data" v-if="noticeList.length === 0">
				<image class="empty-image" src="/static/images/empty-data.png" mode="aspectFit"></image>
				<text class="empty-text">暂无公告数据</text>
			</view>
			
			<view class="notice-item" v-for="(item, index) in noticeList" :key="index" @click="viewNoticeDetail(item)">
				<view class="notice-content">
					<view class="notice-header">
						<view class="notice-title-row">
							<text class="notice-title">{{ item.title }}</text>
							<text class="notice-importance" :class="[getImportanceClass(item.importance)]">{{ item.importance }}</text>
						</view>
						<view class="notice-info">
							<text class="notice-date">发布: {{ formatDate(item.publishDate) }}</text>
							<text class="notice-category">{{ item.category }}</text>
							<text class="notice-status" :class="[getStatusClass(item)]">{{ getStatusText(item) }}</text>
						</view>
					</view>
					<view class="notice-summary">{{ item.summary }}</view>
					<view class="notice-stats">
						<text class="stats-item">阅读: {{ item.viewCount || 0 }}</text>
					</view>
				</view>
				<view class="notice-actions">
					<view class="action-btn edit-btn" @click.stop="editNotice(item)">
						<text class="action-icon">✏️</text>
						<text class="action-text">编辑</text>
					</view>
					<view class="action-btn delete-btn" @click.stop="confirmDeleteNotice(item)">
						<text class="action-icon">🗑️</text>
						<text class="action-text">删除</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-container" v-if="loading">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore && !loading && noticeList.length > 0" @click="loadMore">
			<text>加载更多</text>
		</view>
		
		<view class="load-all" v-if="!hasMore && noticeList.length > 0">
			<text>已加载全部数据</text>
		</view>
	</view>
</template>

<script>
	import { getToken } from '@/utils/tokenManager.js';
	
	export default {
		data() {
			// 获取当前日期
			const now = new Date();
			const year = now.getFullYear();
			const month = String(now.getMonth() + 1).padStart(2, '0');
			const day = String(now.getDate()).padStart(2, '0');
			const today = `${year}-${month}-${day}`;
			
			return {
				userInfo: null,
				userId: '',
				loading: true,
				refreshing: false,
				noticeList: [],
				page: 1,
				limit: 10,
				total: 0,
				hasMore: true,
				
				// 当前日期
				today: today,
				
				// 筛选参数
				filterParams: {
					title: '',
					category: '',
					status: '',
					startDate: '',
					endDate: ''
				},
				
				// 下拉选项
				categoryOptions: ['全部', '赛事通知', '规则解读', '裁判培训', '其他通知'],
				categoryIndex: 0,
				
				statusOptions: ['全部', '已发布', '已过期', '未发布'],
				statusIndex: 0
			}
		},
		onLoad() {
			// 直接加载公告列表，不依赖用户信息
			this.directFetchNotices();
			// 获取用户ID，用于删除等操作
			this.getUserId();
		},
		onPullDownRefresh() {
			this.refreshData();
		},
		methods: {
			// 直接从云端获取公告列表，不依赖用户信息
			directFetchNotices() {
				this.loading = true;
				this.noticeList = [];
				
				console.log('正在直接获取公告列表...');
				
				// 从本地存储获取用户ID
				const userInfoStr = uni.getStorageSync('userInfo');
				let userId = '';
				if (userInfoStr) {
					try {
						const userInfo = JSON.parse(userInfoStr);
						userId = userInfo._id || userInfo.userId || userInfo.id || '';
						this.userId = userId;
					} catch (e) {
						console.error('解析用户信息失败', e);
					}
				}
				
				if (!userId) {
					userId = this.userId;
				}
				
				console.log('当前用户ID:', userId);
				
				(async () => {
					try {
						const noticeService = uniCloud.importObject('notice-service');
						const res = await noticeService.getNotices(
							1, // page
							20, // limit
							'', // category
							null, // showInHome
							'', // title
							'', // status
							userId // creatorId
						);
						
						this.loading = false;
						console.log('云对象返回结果:', res);
						
						if (res && res.code === 0) {
							this.noticeList = res.data || [];
							this.total = res.total || 0;
							this.hasMore = this.noticeList.length < this.total;
							
							if (this.noticeList.length > 0) {
								this.page = 2;
							}
						} else {
							uni.showToast({
								title: res?.message || '获取数据失败',
								icon: 'none'
							});
						}
					} catch (err) {
						this.loading = false;
						console.error('调用云对象失败:', err);
						
						uni.showToast({
							title: '网络错误，请重试',
							icon: 'none'
						});
					}
				})();
			},
			
			// 下拉刷新数据
			refreshData() {
				this.refreshing = true;
				this.directFetchNotices();
			},
			
			// 加载更多
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.loading = true;
					
					(async () => {
						try {
							const noticeService = uniCloud.importObject('notice-service');
							const res = await noticeService.getNotices(
								this.page, // page
								10, // limit
								'', // category
								null, // showInHome
								'', // title
								'', // status
								this.userId // creatorId
							);
							
							this.loading = false;
							
							if (res && res.code === 0) {
								const newData = res.data || [];
								this.noticeList = [...this.noticeList, ...newData];
								this.total = res.total || 0;
								this.hasMore = this.noticeList.length < this.total;
								
								if (newData.length > 0) {
									this.page++;
								}
							} else {
								uni.showToast({
									title: res?.message || '获取数据失败',
									icon: 'none'
								});
							}
						} catch (err) {
							this.loading = false;
							console.error('调用云对象失败:', err);
							
							uni.showToast({
								title: '网络错误，请重试',
								icon: 'none'
							});
						}
					})();
				}
			},
			
			// 查看公告详情
			viewNoticeDetail(notice) {
				uni.navigateTo({
					url: `/packageStudy/study/notice-detail?id=${notice._id}&from=management`
				});
			},
			
			// 编辑公告
			editNotice(notice) {
				if (!notice || !notice._id) {
					uni.showToast({
						title: '无效的公告ID',
						icon: 'none'
					});
					return;
				}
				
				console.log('准备编辑公告, ID:', notice._id);
				
				// 将ID保存到本地存储，以防页面跳转过程中参数丢失
				uni.setStorageSync('edit_notice_id', notice._id);
				
				// 使用更可靠的传参方式，跳转到notice-upload页面并添加编辑模式参数
				const url = `/packageadmin/admin/notice-upload?id=${encodeURIComponent(notice._id)}&mode=edit&t=${Date.now()}`;
				console.log('跳转URL:', url);
				
				uni.navigateTo({
					url: url,
					fail: (err) => {
						console.error('页面跳转失败:', err);
						uni.showToast({
							title: '页面跳转失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 确认删除公告
			confirmDeleteNotice(notice) {
				uni.showModal({
					title: '确认删除',
					content: `确定要删除公告"${notice.title}"吗？此操作不可恢复。`,
					confirmText: '删除',
					confirmColor: '#ff4d4f',
					success: (res) => {
						if (res.confirm) {
							this.deleteNotice(notice);
						}
					}
				});
			},
			
			// 获取用户ID，用于删除等操作
			getUserId() {
				// 从本地存储获取用户信息
				const userInfoStr = uni.getStorageSync('userInfo');
				if (userInfoStr) {
					try {
						const userInfo = JSON.parse(userInfoStr);
						this.userId = userInfo._id || userInfo.userId || userInfo.id || '';
						console.log('已获取用户ID:', this.userId);
					} catch (e) {
						console.error('解析用户信息失败', e);
						this.getCloudUserId();
					}
				} else {
					// 本地没有，从云端获取
					this.getCloudUserId();
				}
			},
			
			// 从云端获取用户ID
			async getCloudUserId() {
									try {
						const userService = uniCloud.importObject('user-service');
						const res = await userService.getUserInfo(getToken());
					
					if (res && res.code === 0 && res.data) {
						this.userId = res.data.userId || res.data._id || '';
							console.log('已从云端获取用户ID:', this.userId);
						} else {
						console.error('获取用户ID失败:', res);
						}
				} catch (err) {
					console.error('调用获取用户信息云对象失败', err);
					}
			},
			
			// 删除公告
			deleteNotice(notice) {
				uni.showLoading({
					title: '删除中...'
				});
				
				// 获取token
				const token = getToken();
				if (!token) {
					uni.hideLoading();
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				
				// 如果没有用户ID，先获取
				if (!this.userId) {
					this.getUserId();
					uni.showToast({
						title: '请稍后再试',
						icon: 'none'
					});
					uni.hideLoading();
					return;
				}
				
				console.log('删除公告:', notice._id, '创建者ID:', this.userId);
				
				(async () => {
					try {
						const noticeService = uniCloud.importObject('notice-service');
						// 修改参数传递方式：传递3个独立参数而不是对象
						const res = await noticeService.deleteNotice(notice._id, this.userId, token);
						
						uni.hideLoading();
						console.log('删除公告返回:', res);
						
						if (res.code === 0) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							
							// 从列表中移除该公告
							const index = this.noticeList.findIndex(item => item._id === notice._id);
							if (index > -1) {
								this.noticeList.splice(index, 1);
							}
						} else {
							uni.showModal({
								title: '删除失败',
								content: res.message || '未知错误',
								showCancel: false
							});
						}
					} catch (err) {
						uni.hideLoading();
						console.error('删除公告失败:', err);
						
						uni.showModal({
							title: '删除失败',
							content: '网络错误，请重试',
							showCancel: false
						});
					}
				})();
			},
			
			// 执行搜索
			handleSearch() {
				this.directFetchNotices();
			},
			
			
			// 绑定分类选择
			bindCategoryChange(e) {
				this.categoryIndex = e.detail.value;
				this.filterParams.category = this.categoryOptions[this.categoryIndex];
				this.directFetchNotices();
			},
			
			// 绑定状态选择
			bindStatusChange(e) {
				this.statusIndex = e.detail.value;
				const statusMap = {
					'0': '',
					'1': 'published',
					'2': 'expired',
					'3': 'draft'
				};
				this.filterParams.status = statusMap[this.statusIndex];
				this.directFetchNotices();
			},
			
			// 绑定开始日期
			bindStartDateChange(e) {
				this.filterParams.startDate = e.detail.value;
				
				// 如果结束日期早于开始日期，清空结束日期
				if (this.filterParams.endDate && this.filterParams.endDate < this.filterParams.startDate) {
					this.filterParams.endDate = '';
				}
				
				this.directFetchNotices();
			},
			
			// 绑定结束日期
			bindEndDateChange(e) {
				this.filterParams.endDate = e.detail.value;
				this.directFetchNotices();
			},
			
			// 导航到指定页面
			navigateTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			
			// 获取重要程度样式类
			getImportanceClass(importance) {
				switch(importance) {
					case '重要':
						return 'importance-high';
					case '普通':
					default:
						return 'importance-normal';
				}
			},
			
			// 获取状态样式类
			getStatusClass(notice) {
				const now = new Date().getTime();
				const endDate = notice.endDate ? new Date(notice.endDate).getTime() : null;
				
				if (endDate && now > endDate) {
					return 'status-expired';
				} else {
					return 'status-published';
				}
			},
			
			// 获取状态文本
			getStatusText(notice) {
				const now = new Date().getTime();
				const endDate = notice.endDate ? new Date(notice.endDate).getTime() : null;
				
				if (endDate && now > endDate) {
					return '已过期';
				} else {
					return '已发布';
				}
			},
			
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				
				const date = new Date(dateStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				
				return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style>
	@import "../admin/app.css";
	
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		margin-bottom: 20rpx;
	}
	
	.header-left {
		display: flex;
		flex-direction: column;
	}
	
	.header-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.header-desc {
		font-size: 24rpx;
		color: #999;
		margin-top: 6rpx;
	}
	
	.add-btn {
		background-color: #1BAE76;
		color: #fff;
		border: none;
		padding: 16rpx 30rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		line-height: 1.5;
	}
	
	.filter-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.search-box {
		position: relative;
		margin-bottom: 20rpx;
	}
	
	.search-box input {
		width: 100%;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 0 80rpx 0 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}
	
	.search-icon {
		position: absolute;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
		font-size: 32rpx;
	}
	
	.filter-options {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
	}
	
	.filter-picker {
		margin-right: 20rpx;
		margin-bottom: 10rpx;
	}
	
	.picker-item {
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		padding: 10rpx 20rpx;
		border-radius: 6rpx;
	}
	
	.picker-label {
		color: #666;
		font-size: 24rpx;
		margin-right: 8rpx;
	}
	
	.picker-value {
		color: #333;
		font-size: 24rpx;
		max-width: 160rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.filter-reset {
		color: #1BAE76;
		font-size: 24rpx;
		padding: 10rpx 20rpx;
		margin-left: auto;
	}
	
	.notice-list {
		margin-bottom: 30rpx;
	}
	
	.notice-item {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		display: flex;
		flex-direction: column;
	}
	
	.notice-content {
		flex: 1;
	}
	
	.notice-header {
		margin-bottom: 16rpx;
	}
	
	.notice-title-row {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}
	
	.notice-title {
		flex: 1;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-right: 10rpx;
	}
	
	.notice-importance {
		font-size: 22rpx;
		padding: 2rpx 10rpx;
		border-radius: 4rpx;
	}
	
	.importance-high {
		background-color: #fff1f0;
		color: #ff4d4f;
	}
	
	.importance-normal {
		background-color: #f0f0f0;
		color: #999;
	}
	
	.notice-info {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}
	
	.notice-date, .notice-category, .notice-status {
		font-size: 24rpx;
		color: #999;
		margin-right: 20rpx;
	}
	
	.status-published {
		color: #52c41a;
	}
	
	.status-scheduled {
		color: #1890ff;
	}
	
	.status-expired {
		color: #999;
	}
	
	.status-draft {
		color: #fa8c16;
	}
	
	.notice-summary {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 16rpx;
		line-height: 1.5;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}
	
	.notice-stats {
		display: flex;
		align-items: center;
	}
	
	.stats-item {
		font-size: 24rpx;
		color: #999;
		margin-right: 20rpx;
	}
	
	.notice-actions {
		display: flex;
		padding-top: 16rpx;
		margin-top: 16rpx;
		border-top: 1px solid #f0f0f0;
	}
	
	.action-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 10rpx 20rpx;
		border-radius: 6rpx;
		margin-right: 20rpx;
	}
	
	.edit-btn {
		background-color: #e6f7ff;
		color: #1890ff;
	}
	
	.delete-btn {
		background-color: #fff1f0;
		color: #ff4d4f;
	}
	
	.action-icon {
		font-size: 28rpx;
		margin-right: 8rpx;
	}
	
	.action-text {
		font-size: 26rpx;
	}
	
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
	}
	
	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 6rpx solid #f3f3f3;
		border-top: 6rpx solid #1BAE76;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	
	.loading-text {
		font-size: 28rpx;
		color: #999;
		margin-top: 20rpx;
	}
	
	.load-more, .load-all {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.load-more {
		color: #1BAE76;
	}
	
	.empty-data {
		padding: 100rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
</style> 
